package com.gpscookie.vocabularystory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.client.CookieStore;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.telephony.TelephonyManager;
import android.util.Log;

public enum Utils {
	INSTANCE;
	CookieStore Cookie = null;
	public int cache_life = -1;
	public SharedPreferences sp;
	public String user = null;	
	public String secret = null;
	public boolean enableGPS = false;
	public int pageSize = 6;
	public int pageNum = 10;
	public String language;
	public long threshhold = 3000;
	public int timeout = 30;
	public String deviceid = null;
	public String password;
	public Book currentBook = null;
	public TextToSpeech tts = null;
	
	public static int NETWORKERROR = 100;
	public static String BARCODE = "barcode";
	public static String NAME = "name";
	public static String ERROR = "error";	
	public static String MSG = "msg";	
	public static String RESULT = "result";	
	public static String DESC = "description";	
	public static String AVERATING = "averating";	
	public static String RATINGCOUNT = "ratingcount";	
	public static String JSONNULL = "{\"error\":1,\"msg\":\"invalid json\"}";
	public static String JSONERROR = "{\"error\":%d,\"msg\":\"%s\"}";
	public int chooseserver = 1;	//0 appspot, 1 delicaterock, 2 gpscookie
	
	public long howLongTillNow(String time) {
		try {
			Calendar now = Calendar.getInstance();
			Date b;			
			b = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time);
			Calendar before = Calendar.getInstance();
			before.setTime(b);
			//System.out.println(now);
			//System.out.println(before);
			long diffMins = (now.getTimeInMillis() - before.getTimeInMillis()) / (60 * 1000);
			return diffMins;
		} catch (ParseException e) {
			return 0;
		}
	}	
	
	public boolean checkJSONResult(String result) {
		if (result==null) {
			return false;
		}
		try {
			JSONObject obj = new JSONObject(result);
			if (obj.getInt("error")==0) {
				return true;
			} else {
				Log.e("checkJSONResult:", obj.getString("msg"));
				return false;
			}
		} catch (JSONException e) {
			return false;
		}
	}
	
	public String md5(String txt) {
		  String s = null;
		  if (txt==null) {
			  return null;
		  }
		  char hexDigits[] = {       
		     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',  'e', 'f'};
		   try
		   {
		    java.security.MessageDigest md = java.security.MessageDigest.getInstance( "MD5" );
		    md.update( txt.getBytes() );
		    byte tmp[] = md.digest();         
		    char str[] = new char[16 * 2];   
		    int k = 0;                       
		    for (int i = 0; i < 16; i++) {   
		                                     
		     byte byte0 = tmp[i];            
		     str[k++] = hexDigits[byte0 >>> 4 & 0xf];  
		                                              
		     str[k++] = hexDigits[byte0 & 0xf];       
		    }
		    s = new String(str);                      

		   }catch( Exception e )
		   {
		    e.printStackTrace();
		   }
		   return s;
	}

	private String scramble(String txt) {
		if (null == txt || txt.length()<=0) {
			return "";
		} else {
			StringBuffer tmp = new StringBuffer();
			for (char t: txt.toCharArray()) {
				tmp.append(String.valueOf((int)t));
			}
			return tmp.toString();
		}
	}	
	
	public String removeHTMLTags(String html) {
		String no = html.replaceAll("\\<.*?\\>", "");
		return no;
	}
	
	public String findProductNameTag(String html) {
		String rtn = null;
		if (html!=null) {
			Pattern pb = Pattern.compile("\\<p>\\s*?\\<b>");
			Pattern pe = Pattern.compile("\\<\\/b>\\s*?\\<\\/p>");
			Matcher mb = pb.matcher(html);
			Matcher me = pe.matcher(html);
			if (mb.find() && me.find()) {
				rtn = html.substring(mb.end(), me.start());
				if (rtn.contains("href")) {
					rtn = removeHTMLTags(rtn).trim();
					Log.i("Utils.findProductNameTag:", rtn);
				} else {
					rtn = null;
				}
			}			
		}
		return rtn;
	}
	
	public ArrayList<String> findAllDivTags(String html) {
		ArrayList<String> rtn = new ArrayList<String>();
		if (html!=null) {
			Pattern pb = Pattern.compile("\\<div\\s+?class=.+?\\>");
			Pattern pe = Pattern.compile("\\<\\/div\\>");
			Matcher mb = pb.matcher(html);
			Matcher me = pe.matcher(html);
			while(mb.find() && me.find()) {
				String item = html.substring(mb.end(), me.start());
				if (item.contains("price/list/id")) {
					item = removeHTMLTags(item).trim();
					Log.i("Utils.findAllDivTags:", item);
					rtn.add(item);
				}				
			}
		}
		return rtn;
	}
	
	public int getJSONResultError(JSONObject result) {
		try {
			return result.getInt("error");
		} catch (JSONException e) {
			return -1;
		}
	}
	
	public String getJSONResultMsg(JSONObject result) {
		try {
			return result.getString("msg");
		} catch (JSONException e) {
			return "";
		}		
	}
	
	public JSONArray getJSONResultArray(JSONObject result) {
		try {
			return result.getJSONArray("result");
		} catch (JSONException e) {
			return null;
		}
	}

	public JSONObject getJSONResultObject(JSONObject result) {
		try {
			return result.getJSONObject("result");
		} catch (JSONException e) {
			return null;
		}
	}
	
	protected String loadPreference(Context context) {		
		sp = PreferenceManager.getDefaultSharedPreferences(context);
		if (sp !=null) {
			user = sp.getString("pre_email", user);
			password = sp.getString("pre_secret", password);
			secret = md5(password);
			enableGPS = sp.getBoolean("pre_location", enableGPS);
			pageSize = Integer.parseInt(sp.getString("pre_page_size", String.valueOf(pageSize)));
			language = Locale.getDefault().getLanguage();
			threshhold = Long.parseLong(sp.getString("pre_threshold", "3000"));
		}
		
		TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        deviceid = tm.getLine1Number();
        if (deviceid==null || deviceid.length()==0) {
        	deviceid = tm.getDeviceId();
        	if (deviceid==null || deviceid.length()==0) {
        		deviceid = tm.getSimSerialNumber();
        	}
        	if (deviceid==null || deviceid.length()==0) {
        		deviceid = tm.getSubscriberId();
        	}
        	if (deviceid==null || deviceid.length()==0) {
        		deviceid="n/a";
        	}        	
        }        
        Log.i("...device ID...", deviceid);        
        return user;
	}
	
	public String composeStoryListURL(String key, String entry, int size, int offset) {
		return String.format("http://vocabularystory.appspot.com/story/list?book=%s&entry=%s&format=json&limit=%d&offset=%d",
				key, entry, size, offset);
	}
	
	public String composeEntryListURL(String key, int size, int offset) {
		switch (chooseserver) {
			case 0:
				return String.format("http://vocabularystory.appspot.com/entry/list?book=%s&limit=%d&offset=%d&format=json", key, size, offset);
			case 1:
				return String.format("http://www.delicaterock.com/php/vocabularystory_entry_list.php?book=%s&limit=%d&offset=%d&format=json", key, size, offset);
			case 2:
				return String.format("http://www.gpscookie.cn/upload/%s.json", key);
			default:
				return String.format("http://vocabularystory.appspot.com/entry/list?book=%s&limit=%d&offset=%d&format=json", key, size, offset);
		}
	}
	
	public String composeBookListHTMLURL() {
		return "http://www.gpscookie.cn/booklist.html";
	}
	
	public String composeBookListURL() {
		switch (chooseserver) {
			case 0:
				return "http://vocabularystory.appspot.com/book/list?format=json";
			case 1:
				return "http://www.delicaterock.com/php/vocabularystory_book_list.php?format=json";
			case 2:
				return "http://www.gpscookie.cn/upload/booklist.json";
			default:
				return "http://vocabularystory.appspot.com/book/list?format=json";
		}
	}
	
	public String composeAddStoryURL(String book, String entry) {
		return String.format("http://vocabularystory.appspot.com/story/create?book=%s&entry=%s", book, entry);
	}
}
